package com.cbd.rabbitmq;

import com.alibaba.fastjson.JSON;
import com.cbd.entity.OpLogEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author BingBing
 * @desc 消息生成者类
 * @date 2024/11/14 11:38
 */
@Component
@Slf4j
public class MyMQProducer {

    @Resource
    private MyMQConfirmCallback myMQConfirmCallback;

    @Resource
    private MyMQReturnCallBack myMQReturnCallback;

    @Resource  // RabbitTemplate 封装了RabbitMQ的API，包括发送消息、接收消息等等
    private RabbitTemplate rabbitTemplate;

    /**
     * 发送消息
     * @param opLogEntity 消息内容
     */
    public void send(OpLogEntity opLogEntity) {
        CorrelationData correlationData = new CorrelationData("id" + System.currentTimeMillis());
        rabbitTemplate.setConfirmCallback(myMQConfirmCallback);
        rabbitTemplate.setReturnsCallback(myMQReturnCallback);

        // 将opLogEntity对象转换为json字符串
        String message = JSON.toJSONString(opLogEntity);
        log.info("消息内容：{}", message);
        // 发送消息
        rabbitTemplate.convertAndSend("opExchange", "opRoutingKey", message, correlationData);
    }
}
